<template>
  <div class="channel-management">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>渠道管理</span>
        <div style="float: right;">
          <el-button 
            type="primary" 
            size="small" 
            icon="el-icon-plus"
            @click="handleAdd"
            style="margin-right: 8px;">
            新增渠道
          </el-button>
          <el-button 
            type="success" 
            size="small" 
            icon="el-icon-download"
            @click="exportData"
            :loading="exportLoading">
            导出CSV
          </el-button>
        </div>
      </div>

      <!-- 筛选条件 -->
      <div class="filter-section" style="margin-bottom: 20px;">
        <el-form :inline="true" :model="filterForm" size="small">
          <el-form-item label="渠道值">
            <el-input 
              v-model="filterForm.value" 
              placeholder="请输入渠道值" 
              style="width: 150px;"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item label="渠道名称">
            <el-input 
              v-model="filterForm.name" 
              placeholder="请输入渠道名称" 
              style="width: 150px;"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        :data="filteredChannels"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        v-loading="loading"
      >
        <el-table-column prop="value" label="渠道值" width="120" sortable></el-table-column>
        <el-table-column prop="name" label="渠道名称" min-width="200"></el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" style="margin-top: 20px; text-align: center;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm">
      <el-form
        :model="form"
        :rules="formRules"
        ref="form"
        label-width="100px">
        <el-form-item label="渠道值" prop="value">
          <el-input-number 
            v-model="form.value" 
            :min="0" 
            placeholder="请输入渠道值" 
            style="width: 100%;"
            :disabled="isEdit">
          </el-input-number>
          <div class="form-tip" v-if="isEdit">渠道值不可修改</div>
        </el-form-item>
        <el-form-item label="渠道名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入渠道名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            type="textarea" 
            v-model="form.description" 
            placeholder="请输入渠道描述"
            :rows="3">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '新增' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { exportDataToCsv } from '@/utils/export'
import channelManager from '@/utils/channelManager'

export default {
  name: 'ChannelManagement',
  data() {
    return {
      channels: [
        { 
          value: 0, 
          name: '全部渠道', 
          description: '用于查询所有渠道数据'
        },
        { 
          value: 1, 
          name: '官方渠道', 
          description: '官方渠道'
        },
        { 
          value: 2, 
          name: '合作渠道A', 
          description: '合作渠道A'
        },
        { 
          value: 3, 
          name: '合作渠道B', 
          description: '合作渠道B'
        },
        { 
          value: 4, 
          name: '推广渠道', 
          description: '推广渠道'
        },
        { 
          value: 5, 
          name: '内测渠道', 
          description: '内测渠道'
        },
        { 
          value: 6, 
          name: '测试渠道', 
          description: '测试渠道'
        },
      ],
      filteredChannels: [],
      loading: false,
      exportLoading: false,
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      submitLoading: false,
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 筛选
      filterForm: {
        value: '',
        name: ''
      },
      
      // 表单
      form: {
        value: null,
        name: '',
        description: ''
      },
      
      // 验证规则
      formRules: {
        value: [
          { required: true, message: '请输入渠道值', trigger: 'blur' },
          { type: 'number', message: '渠道值必须为数字', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入渠道名称', trigger: 'blur' },
          { min: 2, max: 50, message: '渠道名称长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  
  mounted() {
    this.loadChannels()
    // 将渠道数据同步到全局管理工具
    this.syncChannelsToGlobal()
    
    // 延迟再次同步，确保其他页面能获取到数据
    this.$nextTick(() => {
      setTimeout(() => {
        this.syncChannelsToGlobal()
        console.log('ChannelManagement: 延迟同步渠道数据完成')
      }, 100)
    })
  },
  
  methods: {
    // 将渠道数据同步到全局管理工具
    syncChannelsToGlobal() {
      channelManager.setChannels(this.channels)
    },

    // 加载渠道数据
    loadChannels() {
      this.loading = true
      try {
        this.applyFilter()
        // 每次加载数据后都同步到全局
        this.syncChannelsToGlobal()
      } catch (error) {
        console.error('加载渠道数据失败:', error)
        this.$message.error('加载渠道数据失败')
      } finally {
        this.loading = false
      }
    },
    
    // 应用筛选
    applyFilter() {
      let filtered = [...this.channels]
      
      // 按渠道值筛选
      if (this.filterForm.value !== '') {
        filtered = filtered.filter(channel => 
          channel.value.toString().includes(this.filterForm.value.toString())
        )
      }
      
      // 按渠道名称筛选
      if (this.filterForm.name) {
        filtered = filtered.filter(channel => 
          channel.name.toLowerCase().includes(this.filterForm.name.toLowerCase())
        )
      }
      
      this.total = filtered.length
      
      // 分页
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      this.filteredChannels = filtered.slice(start, end)
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.applyFilter()
    },
    
    // 重置筛选
    resetFilter() {
      this.filterForm = {
        value: '',
        name: ''
      }
      this.currentPage = 1
      this.applyFilter()
    },
    
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.applyFilter()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.applyFilter()
    },
    
    // 新增
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增渠道'
      this.form = {
        value: null,
        name: '',
        description: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    
    // 编辑
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑渠道'
      this.form = {
        value: row.value,
        name: row.name,
        description: row.description
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    
    // 删除
    handleDelete(row) {
      this.$confirm(`确认删除渠道"${row.name}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.channels.findIndex(channel => channel.value === row.value)
        if (index !== -1) {
          this.channels.splice(index, 1)
          this.loadChannels()
          // 同步到全局管理工具
          this.syncChannelsToGlobal()
          this.$message.success('删除成功')
        }
      }).catch(() => {
        // 取消删除
      })
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            if (this.isEdit) {
              // 编辑
              const index = this.channels.findIndex(channel => channel.value === this.form.value)
              if (index !== -1) {
                this.channels[index] = {
                  value: this.form.value,
                  name: this.form.name,
                  description: this.form.description
                }
                this.$message.success('更新成功')
              } else {
                this.$message.error('渠道不存在')
                return
              }
            } else {
              // 新增 - 检查渠道值是否重复
              if (this.channels.some(channel => channel.value === this.form.value)) {
                this.$message.error('渠道值已存在，请使用其他值')
                return
              }
              
              const newChannel = {
                value: this.form.value,
                name: this.form.name,
                description: this.form.description
              }
              
              this.channels.push(newChannel)
              this.$message.success('新增成功')
            }
            
            this.dialogVisible = false
            this.loadChannels()
            // 同步到全局管理工具
            this.syncChannelsToGlobal()
          } catch (error) {
            console.error('保存失败:', error)
            this.$message.error('保存失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    
    // 重置表单
    resetForm() {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
    },
    
    // 导出数据
    async exportData() {
      this.exportLoading = true
      try {
        const allChannels = this.channels
        
        const columns = [
          { prop: 'value', label: '渠道值' },
          { prop: 'name', label: '渠道名称' },
          { prop: 'description', label: '描述' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `渠道管理_${dateStr}.csv`
        exportDataToCsv(allChannels, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    }
  }
}
</script>

<style scoped>
.channel-management {
  padding: 20px;
}

.filter-section {
  background: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 